<?php
/**
 * Created by PhpStorm.
 * User: alexey
 * Date: 5/22/14
 * Time: 7:40 PM
 */

namespace controller;

include_once("SQLQuery.php");


class SQLManipulator
{

  private static $queries;

  static private function connectDB()
  {
    $host = "localhost";
    $user = "alexey";
    $pass = "alex_lazer";
    $link_id = mysql_connect($host, $user, $pass);
    mysql_select_db('fly', $link_id) or die(mysql_error());
    mysql_query("SET NAMES 'utf8'");
    mysql_query("SET CHARACTER SET 'utf8'");
    return $link_id;
  }

  static private function startTransaction()
  {
    mysql_query("SET AUTOCOMMIT=0");
    mysql_query("BEGIN");
  }

  static private function commitTransaction()
  {
    mysql_query("COMMIT");
  }

  static private function rollbackTransaction()
  {
    mysql_query("ROLLBACK");
  }

  static function init()
  {
    $fileName = "cnf/sql.properties";
    $file = file($fileName);
    self::$queries = self::parse($file);
  }

  static function parse($parseArray)
  {
    $tmpQueryMap = new \SplObjectStorage();
    $arrayLength = count($parseArray);
    $sqlQuery = "";
    $name = "";
    for ($i = 0; $i < $arrayLength; $i++) {
      $parseString = $parseArray[$i];
      if (!stripos($parseString, '/**')) {
        if (stripos($parseString, '!sql')) {
          $name = self::getNameFromString($parseString);
        } else if (stripos($parseString, '/sql')) {
          $sqlQueryInstance = new SQLQuery();
          $sqlQueryInstance->setKey($name);
          $sqlQueryInstance->setQuery($sqlQuery);
          $tmpQueryMap->attach($sqlQueryInstance);
          $sqlQuery = "";
          $name = "";
        } else {
          $sqlQuery = $sqlQuery . $parseString;
        }
      }
    }
    return $tmpQueryMap;
  }

  static function getNameFromString($string)
  {
    $namePosStart = stripos($string, '\'') + 1;
    $namePosEnd = stripos($string, '\'', $namePosStart);
    $name = trim(substr($string, $namePosStart, $namePosEnd - $namePosStart));
    return $name;
  }

  static function getSQLByName($name)
  {
    if (!self::$queries) {
      self::init();
    }

    self::$queries->rewind();
    $count = self::$queries->count();
    for ($i = 0; $i < $count; $i++) {
      if (self::$queries->current()->getKey() == trim($name)) {
        return self::$queries->current()->getQuery();
      }
      self::$queries->next();
    }
  }

  static function execute($queryName, $paramAssocArray)
  {
    $sqlQuery = self::getSQLByName($queryName);
    $paramStartPos = 0;
    while ($paramStartPos = stripos($sqlQuery, '{', $paramStartPos + 1)) {
      $paramStartPos += 1;
      $paramEndPos = stripos($sqlQuery, '}', $paramStartPos);
      if ($paramEndPos) {
        $queryParameter = substr($sqlQuery, $paramStartPos, $paramEndPos - $paramStartPos);
        $sqlQuery = str_replace("{" . $queryParameter . "}", $paramAssocArray[$queryParameter], $sqlQuery);
      }
    }
    self::connectDB();
    self::startTransaction();
    $result = mysql_query($sqlQuery) or die(mysql_error());
    if ($result) {
      self::commitTransaction();
      return $result;
    } else {
      self::rollbackTransaction();
      return null;
    }
  }
} 